package com.cardone.platform.common.function;

import com.cardone.common.cache.util.CacheUtils;
import com.cardone.context.function.Execution1Function;
import com.cardone.security.token.dto.TokenDto;
import com.cardone.security.token.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * Created by c100000002 on 15-2-6.
 */
@Slf4j
public class TokenGenerateForUrlFunction implements Execution1Function<TokenDto, Map<String, Object>> {
    @Override
    public TokenDto execution(Map<String, Object> stringObjectMap) {
        String url = MapUtils.getString(stringObjectMap, "url");

        String clientId = MapUtils.getString(stringObjectMap, "client_id");
        String oldTokenKey = MapUtils.getString(stringObjectMap, "old_token_key");

        TokenDto oldToken = TokenUtils.get(oldTokenKey);

        TokenDto token = new TokenDto().setClientId(clientId).setKey(StringUtils.remove(UUID.randomUUID().toString(), "-"));
        token.setCreateDate(new Date()).setUrl(url);

        if (oldToken != null) {
            token.setId(oldToken.getId());
        }

        CacheUtils.put(TokenUtils.class.getName(), token.getKey(), token);
        CacheUtils.put(clientId, TokenUtils.getTokenParamName(), token.getKey());

        return token;
    }
}
